package com.cndw.kungfu.event;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import com.cndw.asyncsync.DataSyncServer;
import com.cndw.kungfu.ext.LogUtil;

public class StatisticsRobotHandler extends BaseHandler implements Callable<Integer> {

	private final int type;

	private final int milliseconds;

	private final int[] oldNums;

	private int lastTimes = 0;

	public StatisticsRobotHandler(int type, int times, int milliseconds) {
		this.type = type;
		this.milliseconds = milliseconds;
		oldNums = new int[times + 1];
	}

	public void workRun() {
		if (lastTimes >= oldNums.length) {
			return;
		}
		int currentCount = getCount();

		LogUtil.getMain().info("nums " + lastTimes + " : " + currentCount);

		oldNums[lastTimes] = currentCount;

		lastTimes++;

	}

	private int getCount() {
		int currentCount = 0;
		if (type >= 0) {
			currentCount = DataSyncServer.getInstance().size();
		} else {

		}
		return currentCount;
	}

	public int avg() {
		int allNum = 0;
		int allTimes = 0;
		for (int i = 1; i < lastTimes; i++) {
			allNum += oldNums[i];
			allTimes++;
		}
		allNum -= oldNums[0] * allTimes;
		if (type == 1) {
			allNum += DataSyncServer.getInstance().getMinuteSpeed() * allTimes * milliseconds / 1000 / 60;
			LogUtil.getMain().info("one minute consume " + DataSyncServer.getInstance().getMinuteSpeed());
		}
		return allNum / allTimes;
	}

	@Override
	public Integer call() throws Exception {
		if (getCount() <= 100) {
			LogUtil.getMain().info("err ");
			return 0;
		}

		while (lastTimes < oldNums.length) {
			try {
				workRun();
				TimeUnit.MILLISECONDS.sleep(milliseconds);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		int avg = avg();
		LogUtil.getMain().info("avg " + avg + ": minute" + (avg * (3600 / milliseconds)));

		return avg;
	}

	@Override
	protected void finalize() throws Throwable {
		int avg = avg();
		LogUtil.getMain().info("type " + type + "  avg " + avg);
		super.finalize();
	}

}
